<template>
	<view class="login">
		<zero-custom-bar title="特安练习宝典" :singleIcon="true"></zero-custom-bar>
		<view class="login-box">
			<image class="logo" src="https://wgcwxmin.oss-cn-shanghai.aliyuncs.com/images/2025-07-02/logo.png" mode="">
			</image>
			<view class="login-box-title">
				<text class="slogan">您好，欢迎登录!</text>
				<text class="slogan2">已经购买学员请使用身份证号码登录</text>
			</view>
			<up-form ref="upForm" :model="user" >
				<view class="login-userinfo">
					<view class="login-nickname">
						<view class="login-input">
							<up-form-item prop="username">
								<up-input v-model="user.username" placeholder="请输入身份证号码/手机号码" border="none"
									:fontSize="'30rpx'" :customStyle="{
										'height': '80rpx',
										'lineHeight': '80rpx',
										'fontSize': '30rpx',
										'fontWeight': '700',
										'padding': '0 20rpx',
										'borderRadius': '40rpx'
									}">
									<template #prefix>
										<text style="font-size: 40rpx;margin-right: 20rpx;color: #CBCBCB;" class="iconfont icon-gerenzhongxin"></text>
									</template>
								</up-input>
							</up-form-item>
						</view>
					</view>
					<view class="login-nickname">
						<view class="login-input">
							<up-form-item prop="password">
								<up-input v-model="user.password" type="password" border="none" :fontSize="'30rpx'"
									:customStyle="{
										'height': '80rpx',
										'lineHeight': '80rpx',
										'fontSize': '30rpx',
										'fontWeight': '700',
										'padding': '0 20rpx',
										'borderRadius': '40rpx'
									}" placeholder="请输入密码">
									<template #prefix>
										<text style="font-size: 40rpx;margin-right: 20rpx;color: #CBCBCB;" class="iconfont icon-mima"></text>
									</template>
								</up-input>
							</up-form-item>
						</view>
						<!-- <text @click="forgetPassword"
							style="color:#3b93ee;text-decoration:underline;display: block; font-size: 24rpx;float: right;">忘记密码</text> -->
					</view>
				</view>
			</up-form>
			<view class="login-btn">
				<button class="wxlogin" @click="loginBtn">登录</button>
			</view>
			<!-- <view style="text-align: center;">
				还没账号？<text @click="register" style="color:#3b93ee;text-decoration:underline;display: inline-block;">使用微信账号登录</text>
			</view> -->
			<view class="agreement-box" :class="{ 'shake-animation': isShaking }">
				<view class="custom-checkbox" @click="toggleAgreement">
					<view class="checkbox-icon" :class="{ 'checked': checkboxValue.length > 0 }">
						<text v-if="checkboxValue.length > 0" class="iconfont icon-zhengque1" style="color: #3b93ee;"></text>
					</view>
					<view class="agreement-txt">
						<text>我已阅读并同意</text>
						<navigator class="agreement" url="../userInfo/agreement">《用户协议》、</navigator>
						<navigator class="agreement" url="../userInfo/privacy">《隐私政策》</navigator>
					</view>
				</view>
				<text style="font-size: 22rpx;">特安练习宝典仅供特种作业人员内部使用，学员端v1.0.1</text>
			</view>
			<login-popup @success="registerSuccess" :isBindPhone="isBindPhone" :slogan="slogan" :title="title"
				:tokenNoPhone="userinfo.token" ref="applogin"></login-popup>
		</view>
	</view>
</template>

<script>
import {
	login, getDetail, getWxLogin, putUserUpdate
} from '@/http/user.js'
import { isIdCard } from '@/utils/tools.js'
import loginPopup from '@/components/login-popup/loginPopup.vue'
export default {
	components: {
		loginPopup
	},
	data() {
		return {
			user: {
				username: '',
				password: '',
			},
			userinfo: {
				avatar: '',
				nickname: '',
				gender: null,
				phone: '',
				identity: ''
			},
			wxCode: '',
			isBindPhone: false,
			title: '',
			slogan: '',
			checkboxValue: [],
			rules: {
				username: [
					{
						required: true,
						message: '请输入身份证号码',
						trigger: ['blur', 'change']
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
					{
						min: 6,
						message: '密码长度不能少于6位',
						trigger: ['blur', 'change']
					}
				]
			},
			isShaking: false,
		};
	},
	onLoad() {
		// 检查是否可以无感登录
		this.checkSilentLogin()
	},
	onShow() {

	},
	methods: {
		// 抖动协议框
		shakeAgreement() {
			this.isShaking = true
			setTimeout(() => {
				this.isShaking = false
			}, 500)
		},
		// 检查是否可以无感登录
		async checkSilentLogin() {
			try {
				const token = uni.getStorageSync('token')

				// 检查是否有token
				if (token) {
					// 验证token是否有效
					const res = await getDetail()
					if (res.data) {
						// token正常，更新用户信息并跳转到首页
						uni.setStorageSync('userinfo', res.data)
						uni.switchTab({
							url: '/pages/index/index',
							success: () => {
								uni.showToast({
									title: '登录成功',
									icon: 'success'
								})
							}
						})
						return
					}
				}

				// token无效或不存在，尝试微信登录
				// await this.silentWxLogin()

			} catch (error) {
				console.error('无感登录检查失败:', error)
				// 清除可能无效的存储
				uni.clearStorageSync()
			}
		},

		// 检查用户信息是否完整
		isUserInfoComplete(userInfo) {
			return userInfo &&
				userInfo.phone &&
				userInfo.nickname
		},

		// 无感微信登录
		async silentWxLogin(val) {
			try {
				const loginRes = await this.wxLoginPromise()
				const wxRes = await getWxLogin({ code: loginRes.code, uid: val.id })
				console.log(wxRes, 'wxRes')
				this.userinfo.wechatOpenid = wxRes.data.wechatOpenid
				this.userinfo.sessionKey = wxRes.data.sessionKey

			} catch (error) {
				console.error('无感登录失败:', error)
			}
		},

		// 账号密码登录
		async loginBtn() {
			// 验证协议
			if (this.checkboxValue.length === 0) {
				this.shakeAgreement()
				return uni.showToast({
					title: '请点击阅读协议',
					icon: 'none',
				})
			}

			try {
				// 表单验证
				await this.$refs.upForm.validate()
				uni.showLoading({
					title: '登录中...',
					mask: true
				})

				// 账号密码登录
				const loginRes = await login({
					username: this.user.username,
					password: this.user.password,
				})

				if (!loginRes.data.wechatOpenid) {
					await this.silentWxLogin(loginRes.data)
				}
				// 保存账号密码登录的信息 合并微信登录信息
				console.log(this.userinfo, 'userinfo197');
				// this.userinfo.set({...loginRes.data})
				this.userinfo = {
					...loginRes.data,
					wechatOpenid: this.userinfo.wechatOpenid,
					sessionKey: this.userinfo.sessionKey
				}
				console.log(this.token, 'userinfo207', this.userinfo);

				// this.checkSilentLogin()
				// 使用之前保存的微信登录数据
				if (this.userinfo) {
					// 检查信息完整性
					if (this.isUserInfoComplete(this.userinfo)) {
						// 存入token
						console.log(this.userinfo, 'userinfo215');
						uni.setStorageSync('token', this.userinfo.token)
						console.log(!loginRes.data.wechatOpenid);

						if (!loginRes.data.wechatOpenid) {
							await putUserUpdate({ wechatOpenid: this.userinfo.wechatOpenid, teacher: this.userinfo.teacher })
						}

						const detailRes = await getDetail()
						uni.hideLoading()
						// 信息完整后才存储token和用户信息
						uni.setStorageSync('userinfo', detailRes.data)
						this.navigateBack('登录成功')
					} else {
						console.log(this.userinfo, 'userinfo219');
						// 显示补充信息弹窗
						this.title = '完善信息'
						this.slogan = '-完善信息以获得完整功能-'
						this.$refs.applogin.show(this.userinfo)
					}
				} else {
					uni.showToast({
						title: '登录信息获取失败',
						icon: 'none'
					})
				}

			} catch (error) {
				console.log(error);
				uni.showToast({
					title: error.data.message || '登录失败',
					icon: 'none'
				})
			} finally {
				// uni.hideLoading()
			}
		},

		// Promise化的微信登录
		wxLoginPromise() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: reject
				})
			})
		},

		// 处理登录成功
		async handleLoginSuccess() {
			uni.setStorageSync('token', this.token)
			try {
				const res = await getDetail()
				if (!this.isUserInfoComplete(res.data)) {
					throw new Error('用户信息不完整')
				}
				uni.setStorageSync('userinfo', res.data)
				this.navigateBack('登录成功')
			} catch (error) {
				throw new Error('获取用户信息失败')
			}
		},

		// 返回上一页或首页
		navigateBack(message = '登录成功') {
			const pages = getCurrentPages()
			if (pages.length > 1) {
				uni.navigateBack({
					success: () => {
						uni.showToast({
							title: message,
							icon: 'success'
						})
					}
				})
			} else {
				uni.switchTab({
					url: '/pages/index/index',
					success: () => {
						uni.showToast({
							title: message,
							icon: 'success'
						})
					}
				})
			}
		},
		register() {
			// uni.navigateTo({
			// 	url: '/pages/login/register'
			// })
			console.log(555);

			this.title = '欢迎加入我们！'
			this.slogan = '-加入我们获取更多学习功能-'
			this.userinfo = {
				register: true
			}
			
			// // 使用已有的微信登录数据
			this.$refs.applogin.show(this.userinfo)
		},
		forgetPassword() {
			uni.navigateTo({
				url: '/pages/login/forgetPassword'
			})
		},
		registerSuccess() {
			this.$refs.applogin.close()
			this.navigateBack()
		},
		onChooseAvatar(val) {
			this.userinfo.avatar = val.detail.avatarUrl
		},
		nickBlur(val) {
			this.userinfo.nickname = val.detail.value
		},
		wxLogin() {

		},
		toggleAgreement() {
			this.checkboxValue = this.checkboxValue.length > 0 ? [] : [1]
		},
	}
}
</script>

<style lang="scss" scoped>
page {
	background: linear-gradient(180deg, #B4CDF8, rgba(239, 243, 250, 0));
}

.login {
	background: url('https://wgcwxmin.oss-cn-shanghai.aliyuncs.com/images/2025-07-02/login-bg.png') no-repeat top left / 100% 710rpx;
}

.login-box {

	border-radius: 30rpx 30rpx 0rpx 0rpx;

	padding: 40rpx 70rpx 120rpx 70rpx;

	text-align: center;

	.logo {
		width: 135rpx;
		height: 135rpx;
		border-radius: 35rpx;
		// background: #FB4939;
	}

	.login-box-title {
		// text-align: center;
		margin-top: 50rpx;

		text {
			display: block;
		}

		.slogan {
			font-weight: 600;
			font-size: 42rpx;
			color: #48494A;
		}

		.slogan2 {
			font-weight: 500;
			font-size: 24rpx;
			color: #313131;
			margin-top: 15rpx;
		}
	}

	.login-userinfo {
		margin-top: 40rpx;

		.avatar {
			background: linear-gradient(180deg, #3b93ee, #e7ecf8);
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 0;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.iconfont {
			color: #fff;
			font-size: 80rpx;
		}

		.login-nickname {
			margin-top: 50rpx;
			// width: 450rpx;
			margin-bottom: 30rpx;

			text {
				font-weight: 700;
				font-size: 30rpx;
				color: #2F3133;
				display: block;
				// margin-bottom: 30rpx;
			}

			.login-input {
				// padding: 10rpx 0;
				background: #fff;
				border-radius: 40rpx;
			}


		}
	}

	.login-btn {
		margin-top: 80rpx;
		button {
			width: 520rpx;
			height: 100rpx;
			line-height: 100rpx;
			border-radius: 50rpx;
			font-weight: 700;
			font-size: 30rpx;
			color: #FFFFFF;
			margin-bottom: 30rpx;
		}
		.wxlogin {
			background: linear-gradient(180deg, #4F83F5, #4D82F3, #6B98F9 );
		}
	}
}

.agreement-box {
	position: fixed;
	left: 50%;
	bottom: 40rpx;
	transform: translateX(-50%);
	font-weight: 600;
	font-size: 24rpx;
	color: #A5A5A5;
	text-align: center;
	width: 100%;
	padding: 0 30rpx;
	box-sizing: border-box;

	.custom-checkbox {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		cursor: pointer;

		.checkbox-icon {
			width: 36rpx;
			height: 36rpx;
			border: 2rpx solid #A5A5A5;
			border-radius: 50%;
			margin-right: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s;

			&.checked {
				background: #fff;
				border-color: #3b93ee;
			}

			.icon-check {
				color: #fff;
				font-size: 24rpx;
			}
		}

		.agreement-txt {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.agreement {
			color: #3b93ee;
		}
	}
}

@keyframes shake {

	0%,
	100% {
		transform: translateX(-50%);
	}

	25% {
		transform: translate(-50%, 0) translateX(-8rpx);
	}

	75% {
		transform: translate(-50%, 0) translateX(8rpx);
	}
}

.shake-animation {
	animation: shake 0.5s ease-in-out;
}

.login-input {
	::v-deep .up-form-item__body {
		padding: 0;
	}

	::v-deep .up-form-item__error {
		color: #3b93ee;
		font-size: 24rpx;
		margin-top: 8rpx;
	}
}

::v-deep .up-checkbox-group--row {
	justify-content: center;
}
</style>